struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};


class Solution {
public:
    // 利用环形链表求第一个入环节点方法
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode* fastptr = headB, *slowptr = headB, *ptr = headA;
        while (ptr->next) ptr = ptr->next;
        // 变环形
        ptr->next = headA;

        bool hasCycle = false;
        while (fastptr && slowptr && !hasCycle) {
            fastptr = fastptr->next;
            if (fastptr) fastptr = fastptr->next;
            slowptr = slowptr->next;
            if (fastptr && fastptr == slowptr) hasCycle = true;
        }
        if (!hasCycle) {
            ptr->next = nullptr;
            return nullptr;
        }
        else {
            ListNode* ptr2 = headB;
            while (ptr2 != slowptr) {
                ptr2 = ptr2->next;
                slowptr = slowptr->next;
            }
            ptr->next = nullptr;
            return ptr2;
        }
        

    }
};